package com.framework.foundation.util;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import org.apache.log4j.Logger;

import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * freemarker工具类
 * 
 * @Author: Brin
 * @Date: 2015年10月16日 上午11:10:40
 */
public class FreemarkerKit {
	protected final static Logger LOG = Logger.getLogger(FreemarkerKit.class);

	/**
	 * 渲染模板
	 * 
	 * @param templateContent
	 * @param paramMap
	 * @return
	 * @throws IOException
	 * @throws TemplateException
	 */
	public static String render(String templateContent, Map<String, Object> paramMap) {
		StringWriter writer = new StringWriter();
		try {
			Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
			cfg.setTemplateLoader(new StringTemplateLoader(templateContent));
			cfg.setDefaultEncoding("UTF-8");

			Template template = cfg.getTemplate("");

			template.process(paramMap, writer);
		} catch (IOException e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		} catch (TemplateException e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		}
		return writer.toString();
	}

}

class StringTemplateLoader implements TemplateLoader {

	private String template;

	public StringTemplateLoader(String template) {
		this.template = template;
		if (template == null) {
			this.template = "";
		}
	}

	@Override
	public void closeTemplateSource(Object templateSource) throws IOException {
		((StringReader) templateSource).close();
	}

	@Override
	public Object findTemplateSource(String name) throws IOException {
		return new StringReader(template);
	}

	@Override
	public long getLastModified(Object templateSource) {
		return 0;
	}

	@Override
	public Reader getReader(Object templateSource, String encoding) throws IOException {
		return (Reader) templateSource;
	}

}
